package com.totoro.rabbitmq.ps;

import com.rabbitmq.client.*;
import com.totoro.rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅服务端
 * 发布订阅的实现逻辑时，客户订阅主题，服务端需要把消息发送给所有订阅了主题的客户端
 * 我们通过RabbitMQ提供的dirtct类型的Exchange来实现
 * Created by Niki on 2018/3/30 8:34
 */
public class PSService {
    private static final String EXCHANGE_NAME = "ps_exchange_demo";
    private static final String ROUTING_KEY = "ps_routing_demo";
    private static final String MSG = "Hello RabbitMQ";

    private static void sendMsg() {
        ConnectionFactory connectionFactory = RabbitMQUtil.getConnectionFactory();
        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, MSG.getBytes("utf-8"));

            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        sendMsg();
    }
}

